package com.pyound.controller;

import cn.hutool.core.util.ObjectUtil;
import com.pyound.entity.FastdfsDataEntity;
import com.pyound.service.FastdfsDataService;
import com.pyound.utils.FastDFSUtil;
import com.pyound.utils.R;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

@Api(tags = {"文件系统"})
@RestController
public class FastDFSController {

    @Autowired
    private FastdfsDataService fastdfsDataService;

    @ApiOperation(value = "文件上传")
    @PostMapping(value = "/upload")
    public R<FastdfsDataEntity> upload(@ApiParam(name = "file", value = "文件", required = true) MultipartFile file) {
        try {
            FastdfsDataEntity entity = fastdfsDataService.upload(file.getOriginalFilename(), file.getBytes());
            return R.ok(entity);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @ApiOperation(value = "文件下载")
    @GetMapping(value = "/download/{fileId}")
    public R download(@PathVariable("fileId") Long fileId,
                      HttpServletRequest request,
                      HttpServletResponse response) throws Exception {
        FastdfsDataEntity entity = fastdfsDataService.getById(fileId);
        if (ObjectUtil.isEmpty(entity)) {
            return R.error("文件不存在");
        }
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;fileName=" +
                java.net.URLEncoder.encode(entity.getOriginalFileName(), "UTF-8"));
        InputStream inputStream = FastDFSUtil.downloadFile(entity.getGroupName(), entity.getFilePath());
        ServletOutputStream out = response.getOutputStream();
        byte[] buffer = new byte[1024];
        while (inputStream.read(buffer) != -1) {
            out.write(buffer);
        }
        return R.ok();
    }

    @ApiOperation(value = "文件删除")
    @DeleteMapping(value = "/deleteFile/{fileId}")
    public R deleteFile(@PathVariable("fileId")Long fileId) {
        FastdfsDataEntity entity = fastdfsDataService.getById(fileId);
        if (ObjectUtil.isEmpty(entity)) {
            return R.error("文件不存在");
        }
        FastDFSUtil.deleteFile(entity.getGroupName(),entity.getFilePath());
        fastdfsDataService.removeById(fileId);
        return R.ok(200,"删除成功");
    }

}
